<script setup lang="ts">
  import { onMounted, ref } from "vue";
  import { useUserStore } from "@/stores";

  const userStore = useUserStore();
  const modalVisible = ref(false);
  const users = ref<any>([]);
  const user = ref<any>({});

  onMounted(() => {
    fetchList();
  });

  async function fetchList() {
    users.value = await userStore.getUsers();
  }

  function handleAdd() {
    user.value = {};
    modalVisible.value = true;
  }

  async function handleEdit(record: any) {
    user.value = await userStore.getUser({ id: record.id });
    modalVisible.value = true;
  }

  async function handleRemove(record: any) {
    await userStore.deleteUser({ id: record.id });
    users.value = users.value.filter((item: any) => item.id !== record.id);
  }

  async function handleSave() {
    await userStore.saveUser({ ...user.value });
    modalVisible.value = false;
    fetchList();
  }
</script>

<template>
  <div class="page-container">
    <Breadcrumb :items="['用户管理', '用户列表']"></Breadcrumb>
    <a-card :bordered="false">
      <a-button type="primary" size="small" style="margin-bottom: 16px" @click="handleAdd">新增</a-button>
      <a-table :data="users">
        <template #columns>
          <a-table-column title="用户账号" data-index="username" />
          <a-table-column title="真实姓名" data-index="realName" />
          <a-table-column title="手机号码" data-index="phone" />
          <a-table-column title="创建时间" data-index="createdAt" :width="180" />
          <a-table-column title="更新时间" data-index="updatedAt" :width="180" />
          <a-table-column title="操作" :width="120">
            <template #cell="{ record }">
              <a-space>
                <a-button type="primary" size="small" @click="handleEdit(record)">编辑</a-button>
                <a-popconfirm content="您确认移除此记录么？" position="tr" @ok="handleRemove(record)">
                  <a-button type="primary" size="small" status="danger">移除</a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>
    <a-modal :visible="modalVisible" title="用户信息" @cancel="modalVisible = false" @ok="handleSave">
      <a-form :model="{}" auto-label-width>
        <a-form-item label="用户账号">
          <a-input placeholder="请输入用户账号" v-model="user.username"></a-input>
        </a-form-item>
        <a-form-item label="真实姓名">
          <a-input placeholder="请输入真实姓名" v-model="user.realName"></a-input>
        </a-form-item>
        <a-form-item label="手机号码">
          <a-input placeholder="请输入手机号码" v-model="user.phone"></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
